/*
 * Copyright (c) 2002-2007, Mairie de Paris
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice
 *     and the following disclaimer.
 *
 *  2. Redistributions in binary form must reproduce the above copyright notice
 *     and the following disclaimer in the documentation and/or other materials
 *     provided with the distribution.
 *
 *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * License 1.0
 */
package fr.paris.lutece.plugins.customisation.business.portlet;

import fr.paris.lutece.portal.business.portlet.Portlet;
import fr.paris.lutece.util.sql.DAOUtil;

import java.sql.Timestamp;

import java.util.ArrayList;
import java.util.List;


/**
 * This class provides Data Access methods for PersonalPortlet objects
 */
public class PersonalPortletDAO implements IPersonalPortletDAO
{
    private static final String SQL_QUERY_INSERT_PORTLET = "INSERT INTO customisation_personal_portlet" +
        "( id_portlet, id_portlet_type, name, date_update, status, id_style, accept_alias, date_creation, display_portlet_title, portlet_order, column_no, mode_default, id_tab, mylutece_database_user_id, status_portlet )" +
        "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ";
    private static final String SQL_QUERY_DELETE_PORTLET = "DELETE FROM customisation_personal_portlet WHERE id_portlet = ? AND mylutece_database_user_id = ? AND id_tab = ? ";
    private static final String SQL_QUERY_SELECT_PORTLET = "SELECT * FROM customisation_personal_portlet WHERE id_portlet = ? AND id_tab = ? ";
    private static final String SQL_QUERY_UPDATE_PORTLET = "UPDATE customisation_personal_portlet SET date_update = ? , id_style = ? , accept_alias = ? ," +
        "display_portlet_title = ? , mode_default = ?, portlet_order = ?, column_no = ? WHERE mylutece_database_user_id = ? AND id_portlet = ? AND id_tab = ? ";
    private static final String SQL_QUERY_SELECT_ALL_PORTLET_BY_TAB = "SELECT * FROM customisation_personal_portlet WHERE mylutece_database_user_id = ? AND id_tab = ? ORDER BY portlet_order ";
    private static final String SQL_QUERY_DELETE_PORTLET_BY_TAB = "DELETE FROM customisation_personal_portlet WHERE mylutece_database_user_id = ? AND id_tab = ? ";
    private static final String SQL_QUERY_SELECT_COUNT = "SELECT COUNT(id_portlet) FROM customisation_personal_portlet WHERE id_portlet = ? ";
    private static final String SQL_QUERY_SELECT_ALL_PORTLETS = "SELECT *, COUNT(id_portlet) AS Number FROM customisation_personal_portlet GROUP BY id_portlet ";
    private static final String SQL_QUERY_SELECT_COUNT_BY_USER = "SELECT COUNT(DISTINCT(mylutece_database_user_id)) AS count_by_user FROM customisation_personal_portlet WHERE id_portlet = ? ";
    private static final String SQL_QUERY_SELECT_LAST_ADD = "SELECT MAX(date_creation) AS last_add FROM customisation_personal_portlet WHERE id_portlet = ? ";
    private static final String SQL_QUERY_DELETE_ONE_PORTLET = "DELETE FROM customisation_personal_portlet WHERE id_portlet = ? ";
    private static final String SQL_QUERY_SELECT_PORTLET_ONLY = "SELECT * FROM customisation_personal_portlet WHERE id_portlet = ?";
    private static final String SQL_QUERY_UPDATE_PORTLET_ONLY = "UPDATE customisation_personal_portlet SET date_update = ? , id_style = ? , accept_alias = ? ," +
        "display_portlet_title = ? , mode_default = 0, name = ? WHERE id_portlet = ? ";
    private static final String SQL_QUERY_SELECT_ALL_UNDISPLAYED_PORTLET_BY_PAGE = "SELECT * FROM core_portlet WHERE id_page IS NULL ORDER BY portlet_order ";

    /**
     * Insert a new record in the table
     *
     * @param portlet the personal portlet to insert in the database
     */
    public void insert( PersonalPortlet portlet )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_INSERT_PORTLET );

        daoUtil.setInt( 1, portlet.getId(  ) );
        daoUtil.setString( 2, portlet.getPortletTypeId(  ) );
        daoUtil.setString( 3, portlet.getName(  ) );
        daoUtil.setTimestamp( 4, new Timestamp( new java.util.Date(  ).getTime(  ) ) );
        daoUtil.setInt( 5, portlet.getStatus(  ) );
        daoUtil.setInt( 6, portlet.getStyleId(  ) );
        daoUtil.setInt( 7, portlet.getAcceptAlias(  ) );
        daoUtil.setTimestamp( 8, new Timestamp( new java.util.Date(  ).getTime(  ) ) );
        daoUtil.setInt( 9, portlet.getDisplayPortletTitle(  ) );
        daoUtil.setInt( 10, portlet.getOrder(  ) );
        daoUtil.setInt( 11, portlet.getColumn(  ) );
        daoUtil.setInt( 12, portlet.getModeDefault(  ) );
        daoUtil.setInt( 13, portlet.getTabId(  ) );
        daoUtil.setString( 14, portlet.getUserId(  ) );
        daoUtil.setInt( 15, portlet.getStatusPortlet(  ) );

        daoUtil.executeUpdate(  );

        daoUtil.free(  );
    }

    /**
     * Delete a record from the table
     *
     * @param portlet the personal portlet to be deleted
     */
    public void delete( PersonalPortlet portlet )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE_PORTLET );

        daoUtil.setInt( 1, portlet.getId(  ) );
        daoUtil.setString( 2, portlet.getUserId(  ) );
        daoUtil.setInt( 3, portlet.getTabId(  ) );
        daoUtil.executeUpdate(  );

        daoUtil.free(  );
    }

    /**
     * Delete the records of a specific tab from the table
     *
     * @param portlet the portlet to delete in the database
     */
    public void deleteAllPortletByTab( PersonalPortlet portlet )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE_PORTLET_BY_TAB );

        daoUtil.setString( 1, portlet.getUserId(  ) );
        daoUtil.setInt( 2, portlet.getTabId(  ) );
        daoUtil.executeUpdate(  );

        daoUtil.free(  );
    }

    /**
     * Update the record in the table
     *
     * @param portlet the portlet to update in the database
     */
    public void store( PersonalPortlet portlet )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_UPDATE_PORTLET );
        daoUtil.setTimestamp( 1, portlet.getDateUpdate(  ) );
        daoUtil.setInt( 2, portlet.getStyleId(  ) );
        daoUtil.setInt( 3, portlet.getAcceptAlias(  ) );
        daoUtil.setInt( 4, portlet.getDisplayPortletTitle(  ) );
        daoUtil.setInt( 5, portlet.getModeDefault(  ) );
        daoUtil.setInt( 6, portlet.getOrder(  ) );
        daoUtil.setInt( 7, portlet.getColumn(  ) );
        daoUtil.setString( 8, portlet.getUserId(  ) );
        daoUtil.setInt( 9, portlet.getId(  ) );
        daoUtil.setInt( 10, portlet.getTabId(  ) );

        daoUtil.executeUpdate(  );
        daoUtil.free(  );
    }

    /**
     * Load the data of a personal portlet in a specific tab from the database
     *
     * @param nIdPortlet the portlet identifier
     * @param nIdTab the tab identifier
     * @return the object PersonalPortlet initialized with the data of the database
     */
    public PersonalPortlet load( int nIdPortlet, int nIdTab )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_PORTLET );
        daoUtil.setInt( 1, nIdPortlet );
        daoUtil.setInt( 2, nIdTab );
        daoUtil.executeQuery(  );

        PersonalPortletImpl portlet = new PersonalPortletImpl(  );

        if ( daoUtil.next(  ) )
        {
            portlet.setId( daoUtil.getInt( 1 ) );
            portlet.setPortletTypeId( daoUtil.getString( 2 ) );
            portlet.setName( daoUtil.getString( 3 ) );
            portlet.setDateUpdate( daoUtil.getTimestamp( 4 ) );
            portlet.setStyleId( daoUtil.getInt( 6 ) );
            portlet.setAcceptAlias( daoUtil.getInt( 7 ) );
            portlet.setDisplayPortletTitle( daoUtil.getInt( 9 ) );
            portlet.setOrder( daoUtil.getInt( 10 ) );
            portlet.setColumn( daoUtil.getInt( 11 ) );
            portlet.setModeDefault( daoUtil.getInt( 12 ) );
            portlet.setTabId( daoUtil.getInt( 13 ) );
            portlet.setUserId( daoUtil.getString( 14 ) );
            portlet.setStatusPortlet( daoUtil.getInt( 15 ) );
        }

        daoUtil.free(  );

        return portlet;
    }

    /**
     * Returns a list of portlets according the user identifier and the tab identifier
     *
     * @param strUserName the user identifier
     * @param nIdTab the tab identifier
     * @return the user's portlets in form of Collection
     */
    public List<PersonalPortlet> selectAllPortletByTab( String strUserName, int nIdTab )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_ALL_PORTLET_BY_TAB );
        daoUtil.setString( 1, strUserName );
        daoUtil.setInt( 2, nIdTab );
        daoUtil.executeQuery(  );

        List<PersonalPortlet> listPortlet = new ArrayList<PersonalPortlet>(  );

        while ( daoUtil.next(  ) )
        {
            PersonalPortletImpl portlet = new PersonalPortletImpl(  );
            portlet.setId( daoUtil.getInt( 1 ) );
            portlet.setPortletTypeId( daoUtil.getString( 2 ) );
            portlet.setName( daoUtil.getString( 3 ) );
            portlet.setDateUpdate( daoUtil.getTimestamp( 4 ) );
            portlet.setStyleId( daoUtil.getInt( 6 ) );
            portlet.setAcceptAlias( daoUtil.getInt( 7 ) );
            portlet.setDisplayPortletTitle( daoUtil.getInt( 9 ) );
            portlet.setOrder( daoUtil.getInt( 10 ) );
            portlet.setColumn( daoUtil.getInt( 11 ) );
            portlet.setModeDefault( daoUtil.getInt( 12 ) );
            portlet.setTabId( daoUtil.getInt( 13 ) );
            portlet.setUserId( daoUtil.getString( 14 ) );
            portlet.setStatusPortlet( daoUtil.getInt( 15 ) );
            listPortlet.add( portlet );
        }

        daoUtil.free(  );

        return listPortlet;
    }

    /**
     * Returns the count of a specified portlet
     *
     * @param nIdPortlet the portlet identifier
     * @return the count of a specified portlet
     */
    public int selectCountPortlet( int nIdPortlet )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_COUNT );
        daoUtil.setInt( 1, nIdPortlet );
        daoUtil.executeQuery(  );

        int nCountPortlet = 0;

        while ( daoUtil.next(  ) )
        {
            nCountPortlet = daoUtil.getInt( 1 );
        }

        daoUtil.free(  );

        return nCountPortlet;
    }

    /**
     * Returns the count of a specified portlet by the different user
     *
     * @param nIdPortlet the portlet identifier
     * @return the count of a specified portlet by the different user
     */
    public int selectCountPortletByUser( int nIdPortlet )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_COUNT_BY_USER );
        daoUtil.setInt( 1, nIdPortlet );
        daoUtil.executeQuery(  );

        int nCountPortletByUser = 0;

        while ( daoUtil.next(  ) )
        {
            nCountPortletByUser = daoUtil.getInt( 1 );
        }

        daoUtil.free(  );

        return nCountPortletByUser;
    }

    /**
     * Returns the list of all portlets used in the front office
     *
     * @return the list of all portlets used in the front office
     */
    public List<PersonalPortlet> selectAllPortlets(  )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_ALL_PORTLETS );
        daoUtil.executeQuery(  );

        List<PersonalPortlet> listPortlet = new ArrayList<PersonalPortlet>(  );

        while ( daoUtil.next(  ) )
        {
            PersonalPortletImpl portlet = new PersonalPortletImpl(  );
            portlet.setId( daoUtil.getInt( 1 ) );
            portlet.setPortletTypeId( daoUtil.getString( 2 ) );
            portlet.setName( daoUtil.getString( 3 ) );
            portlet.setDateUpdate( daoUtil.getTimestamp( 4 ) );
            portlet.setStyleId( daoUtil.getInt( 6 ) );
            portlet.setAcceptAlias( daoUtil.getInt( 7 ) );
            portlet.setDisplayPortletTitle( daoUtil.getInt( 9 ) );
            portlet.setOrder( daoUtil.getInt( 10 ) );
            portlet.setColumn( daoUtil.getInt( 11 ) );
            portlet.setModeDefault( daoUtil.getInt( 12 ) );
            portlet.setTabId( daoUtil.getInt( 13 ) );
            portlet.setUserId( daoUtil.getString( 14 ) );
            portlet.setStatusPortlet( daoUtil.getInt( 15 ) );
            portlet.setCount( daoUtil.getInt( 16 ) );
            listPortlet.add( portlet );
        }

        daoUtil.free(  );

        return listPortlet;
    }

    /**
     * Returns the date of the last add for a portlet
     *
     * @param nIdPortlet the portlet identifier
     * @return the date of the last add for a portlet
     */
    public Timestamp selectLastAddition( int nIdPortlet )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_LAST_ADD );
        daoUtil.setInt( 1, nIdPortlet );
        daoUtil.executeQuery(  );

        Timestamp timestampLastAdd = null;

        while ( daoUtil.next(  ) )
        {
            timestampLastAdd = daoUtil.getTimestamp( 1 );
        }

        daoUtil.free(  );

        return timestampLastAdd;
    }

    /**
     * Deletes the portlet specified in all the tabs of users' site
     *
     * @param nPortletId the portlet identifier
     */
    public void deletePortletFromAllTab( int nPortletId )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE_ONE_PORTLET );
        daoUtil.setInt( 1, nPortletId );
        daoUtil.executeUpdate(  );

        daoUtil.free(  );
    }

    /**
     * Returns if the portlet specified exist or not
     *
     * @param nIdPortlet the portlet identifier
     * @return if the portlet specified exist or not
     */
    public boolean checkPortlet( int nIdPortlet )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_PORTLET_ONLY );
        daoUtil.setInt( 1, nIdPortlet );
        daoUtil.executeQuery(  );

        if ( daoUtil.next(  ) )
        {
            daoUtil.free(  );

            return true;
        }

        daoUtil.free(  );

        return false;
    }

    /**
     * Update the records in the table
     *
     * @param portlet the portlet to update in the database
     */
    public void store( Portlet portlet )
    {
        DAOUtil daoUtil = new DAOUtil( SQL_QUERY_UPDATE_PORTLET_ONLY );
        daoUtil.setTimestamp( 1, portlet.getDateUpdate(  ) );
        daoUtil.setInt( 2, portlet.getStyleId(  ) );
        daoUtil.setInt( 3, portlet.getAcceptAlias(  ) );
        daoUtil.setInt( 4, portlet.getDisplayPortletTitle(  ) );
        daoUtil.setString( 5, portlet.getName(  ) );
        daoUtil.setInt( 6, portlet.getId(  ) );

        daoUtil.executeUpdate(  );
        daoUtil.free(  );
    }

    /**
     * Returns the list of published portlets but not displayed on any page
     *
     * @param the identifier of the tab
     * @return the undisplayed portlets in form of Collection
     */
	public List<PersonalPortlet> selectAllUndisplayedPortlet(int nIdTab) {
		DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_ALL_UNDISPLAYED_PORTLET_BY_PAGE );
        daoUtil.executeQuery(  );

        List<PersonalPortlet> listPortlet = new ArrayList<PersonalPortlet>(  );

        while ( daoUtil.next(  ) )
        {
            PersonalPortlet portlet = new PersonalPortletImpl(  );
            portlet.setId( daoUtil.getInt( 1 ) );
            portlet.setTabId( nIdTab );
            portlet.setPortletTypeId( daoUtil.getString( 2 ) );
            portlet.setName( daoUtil.getString( 4 ) );
            portlet.setDateUpdate( daoUtil.getTimestamp( 5 ) );
            portlet.setStatusPortlet( daoUtil.getInt( 6 ) );
            portlet.setOrder( daoUtil.getInt( 7 ) );
            portlet.setColumn( daoUtil.getInt( 8 ) );
            portlet.setStyleId( daoUtil.getInt( 9 ) );
            portlet.setAcceptAlias( daoUtil.getInt( 10 ) );
            portlet.setDisplayPortletTitle( daoUtil.getInt( 12 ) );

            DAOUtil daoUtil2 = new DAOUtil( SQL_QUERY_SELECT_PORTLET );
            daoUtil2.setInt( 1, daoUtil.getInt( 1 ) );
            daoUtil2.setInt( 2, nIdTab );
            daoUtil2.executeQuery(  );
            
            if( daoUtil2.next())
            {
	            portlet.setModeDefault( daoUtil2.getInt( 12 ) );
	            portlet.setUserId( daoUtil2.getString( 14 ) );
            }
 
            listPortlet.add( portlet );
        }

        daoUtil.free(  );

        return listPortlet;
	}
}
